﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using EuroManager.Domain.Simulator.AI.States;
using EuroManager.Domain.Simulator.Engine;
using EuroManager.Domain.Simulator.Helpers;
using EuroManager.Domain.Simulator.Tactics;
using EuroManager.Domain.Simulator.World;

namespace EuroManager.Domain.Simulator.AI
{
    public class PlayerAI : IPlayerAI
    {
        private static readonly float decisionDelay = 0.1f;

        private IPlayer player;
        private IRandomizer random;
        private IState state;
        private Timer decisionTimer;

        public PlayerAI(IPlayer player, IRandomizer random)
        {
            Contract.Requires(player != null);
            Contract.Requires(random != null);

            this.player = player;
            this.random = random;

            player.AI = this;

            decisionTimer = new Timer(decisionDelay);
            Observe();
        }

        public void Update(float elapsedTime)
        {
            decisionTimer.Update(elapsedTime);

            if (decisionTimer.HasPassed)
            {
                decisionTimer.Reset(random.PlayerAIDecisionDelaySalt(decisionDelay));

                state.Execute();

                if (!player.IsMoving)
                {
                    player.TurnToBall();
                }
            }
        }

        public void ChangeState(IState state)
        {
            this.state = state;
        }

        public void Observe()
        {
            ChangeState(new ObserveState(player));
        }

        public void ChaseBall()
        {
            ChangeState(new ChaseBallState(player));
        }

        public void ControlBall()
        {
            ChangeState(new ControlBallState(player, random));
        }
    }
}
